package moonlit.chill.pay.util;

import com.alipay.api.DefaultAlipayClient;
import lombok.extern.slf4j.Slf4j;
import moonlit.chill.pay.vo.PayConfig;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;

/**
 * @author MoonlitChill
 * @date 2024/4/15 16:34
 */
@Slf4j
@Component
public class AliPayClientUtil {

    @Resource(name = "aliClient")
    private Map<String, Object> map;

    public DefaultAlipayClient getAliPayClient(final PayConfig payConfig){
        DefaultAlipayClient alipayClient;
        try {
            if (payConfig.getAliType() == 0){
                //证书模式
                alipayClient = getCertClient(payConfig);
            } else {
                //密钥模式
                alipayClient = getKeyClient(payConfig);
            }
        } catch (Exception e) {
            log.error("支付宝获取DefaultAlipayClient异常", e);
            throw new RuntimeException("支付异常，请联系管理员");
        }
        return alipayClient;
    }

    public String getAliPayCertPath(PayConfig payConfig){
        return map.get(payConfig.getCode() + "_aliPayCertPath").toString();
    }

    private DefaultAlipayClient getKeyClient(PayConfig payConfig) {
        return new DefaultAlipayClient(payConfig.getGateWayUrl(), payConfig.getAppId(), payConfig.getPrivateKey(), "json", "UTF-8", payConfig.getPublicKey(), "RSA2");
    }

    private DefaultAlipayClient getCertClient(PayConfig payConfig) {
        return (DefaultAlipayClient) map.get(payConfig.getCode());
    }
}
